<template>

  <div id="myrightGroup">
     
      <div v-if="false">
         <!-- 头部 -->
           <div class="mySearch_head" >
              <div class="blocks"></div>
              <div class="mySearch_left" @click="selectDivClick">{{messages.title}}</div>
              <div class="mySearch_input form-input-wrap f-l">
                  <!-- <input type="search" name="" id=""> -->
                  <form action="" class="input-kw-form">
                        <input type="search" v-model="value" placeholder="请输入关键词" class="input-kw" v-on:input="changes">
                  </form>
                  <i class="iconfont if-message"></i>
                    <i class="iconfont if-close"></i>
              </div>
              <div class="mySearch_cancel search-cancel f-l" @click="cancelBtn">取消</div>
          </div>
      
      <div class="search_hository">
        <p>最近搜索 <img src="../../../static/cart/Trash@2x.png" alt=""></p>
        <div >
          
          <div class="boxLiDiv" @click="search_content_btn(index)" v-for="(item, index) in search_history_list"  :key="index">
            <div class="liDiv">{{item.content}}</div>
          </div>
          
        </div>
      </div>
        <ul class="search_result" v-show="hiddens" >
          <li v-for="(item, i) in searchTitle" :key="i" @click="resultClick(item)">{{item.title}}</li>
      </ul>

      <div class="showDivWrap" v-if="showDiv">
         <div class="showDiv" >
            <checker
                  default-item-class="demo4-item"
                  selected-item-class="demo4-item-selected"
                  disabled-item-class="demo4-item-disabled">
                    <checker-item v-for="(item,index)  in showDivData" :key="index" :value="item.title" @on-item-click="onItemClick(item.title,item.values)">{{item.title}}</checker-item>
            </checker>
        </div>
    
      </div>
    </div>
     
  

    <div v-else>
          <search-page :searchData="searchData"></search-page>
    </div> 
   
  </div>
</template>

<script>
import {
  Popup,
  TransferDom,
  Checker,
  XHeader,
  CheckerItem,
  Panel,
  XSwitch,
  Search,
  Group,
  Cell,
  Scroller,
  Flexbox,
  FlexboxItem,
  Divider,
  Grid,
  GridItem,
  GroupTitle,
  XInput
} from "vux";
import menu from "./menu.js";
import ExampleStart from "./ExampleStart";

import searchPage from "../../components/toolComponent/searchPage.vue";

import { homeUrl } from "../../components/utils/utils.js";

import $ from "jquery";
$(function() {
  $("#myGrid .weui-grid__icon").height($("#myGrid .weui-grid__icon").width());
});
import axios from "axios";
import qs from "qs";

export default {
  components: {
    Popup,
    TransferDom,
    searchPage,
    Search,
    Group,
    Cell,
    ExampleStart,
    Scroller,
    Flexbox,
    FlexboxItem,
    Divider,
    Grid,
    GridItem,
    GroupTitle,
    XInput,
    Panel,
    XSwitch,
    Checker,
    CheckerItem,
    XHeader
  },
  watch: {
    $route: "getClassifyArr"
  },
  methods: {
    changes(val) {
      this.results = val ? getResults(this.value, this) : [];
    },
    // ‘全部’的div弹出
    selectDivClick() {
      this.showDivFn();
    },
    showDivFn() {
      if (this.showDiv == true) {
        this.showDiv = false;
        this.imgUrl = "../../../static/cart/up.png";
      } else {
        this.showDiv = true;
        this.imgUrl = "../../../static/cart/down.png";
      }
    },
    // 修改分类数据的结构
    modifyMinData(dataArr) {
      // 修改右侧小分类数据的结构
      if (dataArr.length <= 0) {
        return;
      }
      var resultArr = [];
      var previorName = dataArr[0].bigName;
      var tempDic = {};
      var minTempArr = [];
      for (var i = 0; i < dataArr.length; i++) {
        var data = dataArr[i];
        var bigName = data.bigName;
        var minName = data.minName;
        if (bigName != previorName) {
          tempDic["name"] = previorName;
          tempDic["datas"] = minTempArr;
          resultArr.push(tempDic);
          tempDic = {};
          minTempArr = [];
          previorName = bigName;
        } else {
          minTempArr.push(minName);
        }
      }
      this.$data.classifyArr = resultArr;
    },
    // 获取分类数据
    getClassifyArr() {
      // 获取分类数据
      this.$http.get(homeUrl() + "getMinClassify/").then(
        result => {
          if (result.data.status == "ok") {
            // 修改右侧分类数据的结构
            this.modifyMinData(result.data.data);
          }
          this.$vux.toast.text(result.data.message, "bottom");
        },
        error => {
          this.$vux.toast.text("网络请求失败....", "bottom");
          console.log(error);
        }
      );
    },
    onItemClick(itemTitle, itemValue) {
      this.messages.title = itemTitle;
      this.showDiv = false;
      this.keyValue = itemValue;
    },
    setFocus() {
      this.$refs.search.setFocus();
    },
    resultClick(item) {
      this.isSearch = false;
      // this.$data.searchData = JSON.stringify(item);
      var that = this
      let dataList = qs.stringify({
        queryStr: item.title,
        fieldName: item.other
      });
      axios
        .post(homeUrl() + "getGoodsListByQueryString/", dataList, {
          emulateJSON: true
        })
        .then(
          result => {
            that.$data.resultData = result.data.data;
            var searchArr = [];

            if (result.data.status == "ok") {

              that.$data.objArr = result.data.data;
              if (result.data.data.length == 0) {
                that.$data.showAlert = true;
              } else {
                for (var i = 0; i < that.$data.objArr.length; i++) {
                  var searchObj = {};
                  searchObj.src =
                    homeUrl() + that.$data.objArr[i].product_thumb_image;
                  searchObj.title = that.$data.objArr[i].goodsname;
                  searchObj.desc = that.$data.objArr[i].standard;
                  searchObj.goodsid = that.$data.objArr[i].goodsid;
                  searchObj.sellcount = that.$data.objArr[i].sellcount;
                  searchObj.shop_price = that.$data.objArr[i].shop_price;
                  searchObj.rebate = "返利￥" + that.$data.objArr[i].rebate + "元";
                  searchObj.keyWorlds = that.$data.objArr[i].standard;
                  searchArr.push(searchObj);
                }
                // that.$data.shopList = searchArr;
                that.$data.searchData = searchArr
              }
            }
          },
          error => {
            that.$vux.toast.text("网络请求失败....", "bottom");
          }
        );
    },
    onSubmit() {
      this.$refs.search.setBlur();
      this.$vux.toast.show({
        type: "text",
        position: "top",
        text: "on submit"
      });
    },
    onFocus() {
      console.log("on focus");
      this.showDiv = false; //去除div
      // this.$router.push({name: 'goSearch', params: {}})
    },
    onCancel() {
      this.showDiv = false; //去除div
      this.$data.isSearch = false;
    },
    onScroll(event) {
      // console.log(this.$refs.myGroup[0].$el.getBoundingClientRect().height)
      var currentScrollTop = event.top;
      // console.log(this.$refs.groupTitle[0].$el.getBoundingClientRect().top)
      var allGroup = this.$refs.myGroup;
      var calHeight = 0;
      for (var i = 0; i < allGroup.length; i++) {
        calHeight += allGroup[i].$el.getBoundingClientRect().height;
        if (currentScrollTop < calHeight - 100) {
          this.$data.currentLeftIndex = i;
          return;
        }
      }
    },
    onCellClick(clickIndex) {
      var allGroup = this.$refs.myGroup;
      var toTop = 0;
      for (var i = 0; i < clickIndex; i++) {
        toTop += allGroup[i].$el.getBoundingClientRect().height;
      }

      this.$refs.rightScroller.reset({ top: toTop, duration: 1000 });
      this.$data.currentLeftIndex = clickIndex;
    },
    cancelBtn() {
      this.$router.go(-1);
    } , 
    get_search_history_list() {
      var that = this
      this.$http.get(homeUrl() + "searchList/").then(
        result => {
          if (result.data.status == "ok") {
            // 修改右侧分类数据的结构
            that.$data.search_history_list = result.data.data
          }
        },
        error => {
          this.$vux.toast.text("网络请求失败....", "bottom");
          console.log(error);
        }
      );
      
    } , 
    search_content_btn(index){
      var select_search_data = this.$data.search_history_list[index]
      
      var pass_data = {
        "title":select_search_data.content,
        "other":select_search_data.search_type
      }

      this.resultClick(pass_data)
    }
  },
  created() {
    // 组件完成后获取数据,
    // 此时data已经被observed 了
    this.$vux.loading.show({
      text: "loading"
    });
    var that = this;
    setTimeout(() => {
      this.$vux.loading.hide();
    }, 1000);
    this.getClassifyArr();
  },
  mounted() {
    var windowHeight = $(window).height();
    var headerHeight = $(".vux-header").outerHeight();
    var searchBoxHeight = $(".vux-search-box").outerHeight();
    var tabHeight = $(".weui-tabbar").outerHeight();
    this.$data.myHeight =
      windowHeight - headerHeight - searchBoxHeight - tabHeight + "px";

    this.get_search_history_list()
  },
  data() {
    return {
      search_history_list:[] , 
      position: "default",
      showPositionValue: false,
      isSearch: true,
      results: [],
      value: "",
      active: [],
      myCols: 2,
      currentLeftIndex: 0,
      myHeight: "100px",
      classifyArr: [],
      searchData: [],
      showDiv: false,
      showDivData: [
        {
          title: "宝贝",
          values: "goodsname"
        },
        {
          title: "分类",
          values: "standard"
        },
        {
          title: "关键字",
          values: "keywords"
        },
        {
          title: "店铺名",
          values: "shopname"
        }
      ],
      imgUrl: "../../../static/cart/down.png",
      messages: {
        title: "宝贝",
        values: "goodsname"
      },
      hiddens: false,
      searchTitle: "",
      keyValue: "goodsname"
    };
  },

  computed: {
    pageSections() {
      const flatten = (tree, level = 1) => {
        const treeCloned = JSON.parse(JSON.stringify(tree));
        let flattened = [];
        treeCloned.forEach(branch => {
          const { children } = branch;
          delete branch.children;
          branch.level = level;
          flattened.push(branch);
          if (children) {
            flattened = [...flattened, ...flatten(children, level + 1)];
          }
        });
        return flattened;
      };
      return flatten(menu);
    }
  }
};

function getResults(val, that) {
  var rs = [];
  var dataList = qs.stringify({
    queryStr: val,
    fieldName: that.keyValue
  });
  axios
    .post(homeUrl() + "getGoodsBySomething/", dataList, { emulateJSON: true })
    .then(
      result => {
        var objArr = [];
        if (result.data.status == "ok") {
          objArr = result.data.data;
          console.log(that.searchTitle);
          if (that.value != "") {
            that.hiddens = true;
          } else {
            that.hiddens = false;
          }
          for (var i = 0; i < objArr.length; i++) {
            rs.push({
              title: objArr[i],
              other: that.keyValue
            });
          }
          that.searchTitle = rs;
          return rs;
        }
      },
      error => {
        that.$vux.toast.text("网络请求失败....", "bottom");
        console.log(error);
      }
    );
}
</script>
<style lang="less" >
.mySearch_head {
  height: 35px;
  background: #f4f4f4;
  display: flex;
  padding: 6px;
}
.blocks {
  // width: 20px
}
.mySearch_left {
  width: 60px;
  text-align: center;
  background: #ffffff;
  line-height: 35px;
  border-right: 1px solid #cccccc;
  border-radius: 5px;
}
.mySearch_input {
  flex: 3;
  width: 100%;
}
.mySearch_input input {
  width: 100%;
  height: 35px;
  border: none;
  border-radius: 5px;
}
.mySearch_cancel {
  width: 40px;
  text-align: center;
  // background: red;
  line-height: 35px;
}
.hot_search {
  // height: 160px;
  padding: 0.5rem;
  background: #ffffff;
}
.hot_search p,
.search_hository p {
  padding-left: 1rem;
  
  color: #888888;
}
.search_hository p img{
width: 1rem;
float: right;
margin-right: 1rem;
}
.boxLiDiv {
  width: 33%;
  height: 3rem;
  // background: red;
  float: left;
  margin-top:0.5rem; 
}
.liDiv {
  background: #f4f8fb;
  // margin: 0.5rem 1rem;
  width: 80%;
  text-align: center;
  border-radius: 3px;
  height: 2.5rem;
  margin: auto;
  line-height: 2.5rem;
  // display: inline-block;
}
.search_hository {
  padding: 0.5rem;
  // padding-top:8rem; 
  // margin-top: 10px;
  background: #ffffff;
  height: 300px;
}
input[type="search"] {
  border-radius: 5px;
  border: 1px solid #ebebeb; //必须对默认的border:2px inset覆盖，要不然下面的样式也是白搭
  // width: 98%;
  height: 35px;
  outline: none;
  text-align: center;
  // background:url(../../../static/cart/Trash@2x.png) no-repeat right;
  // background-size:2rem; 
}
input[type="search"]::-webkit-input-placeholder {
  // color: blue;
  text-align: center;
}
input[type="search"]::-webkit-search-cancel-button {
  -webkit-appearance: none; //此处只是去掉默认的小×
}
input[type="search"]::-webkit-search-cancel-button {
  -webkit-appearance: none;

  position: relative;
  height: 20px;
  width: 20px;
  border-radius: 50%;
  background-color: #ebebeb;
}

input[type="search"]::-webkit-search-cancel-button:after {
  position: absolute;
  content: "x";
  left: 25%;
  top: -12%;
  font-size: 20px;
  color: #fff;
}
.search_result {
  background: #ffffff;
  position: absolute;
  width: 100%;
  top: 55px;
  // height: ;
  height: 50%;
  overflow: hidden;
}
.search_result li {
  height: 40px;
  border-bottom: 1px solid #ebebeb;
  line-height: 40px;
  padding-left: 15px;
}
.demo4-item {
  background-color: #ddd;
  color: #222;
  width: 3rem;
  text-align: center;
  font-size: 14px;
  padding: 5px 10px;
  margin-right: 10px;
  line-height: 18px;
  border-radius: 10px;
}
.demo4-item-selected {
  background-color: #ff3b3b;
  color: #fff;
}
.demo4-item-disabled {
  color: #999;
}
.selectDiv {
  // margin-top: 46px;
  width: 16%;
  height: 100%;
  border: 1px solid #e6e6ea;
  background: #ffffff;
  float: left;
  text-align: center;
  padding-top: 10px;
  z-index: 10000;
}
.searchDiv {
  width: 80%;
  float: left;
}
.showDiv {
  position: fixed;
  top: 55px;
  width: 100%;
  height: 6.25rem;
  // padding: 0.5rem;
  padding-top: 1.5rem;
  z-index: 9999999999;
  background: #ffffff;
  // box-shadow: 0px 1px 3px #888888;
}
.showDivWrap {
  position: fixed;
  top: 55px;
  width: 100%;
  height: 100%;
  // padding: 0.5rem;
  padding-top: 1.5rem;
  z-index: 9999;
  background: rgba(0, 0, 0, 0.8);
  box-shadow: 0px 1px 3px #888888;
  // opacity: 0.5;
}
</style>
